#!/bin/bash

CANINE_HOME="$HOME/.canine"
CANINE_PATH="$CANINE_HOME/src"
DEFAULT_PORT=3000

function start() {
  local port=${1:-$DEFAULT_PORT}
  cd "$CANINE_PATH" || exit

  # Start the Docker Compose with the specified or default port
  PORT=$port docker compose up -d

  # Poll localhost:$port until it's ready
  echo "Waiting for http://localhost:$port to be available..."
  until curl -s --head "http://localhost:$port" > /dev/null 2>&1; do

    sleep 2
  done

  echo "http://localhost:$port is now available. Opening in browser..."
  # Open the browser (platform-specific command)
  if command -v xdg-open > /dev/null; then
    xdg-open "http://localhost:$port"
  elif command -v open > /dev/null; then
    open "http://localhost:$port"
  else
    echo "Please open http://localhost:$port in your browser."
  fi
}

function stop() {
  cd "$CANINE_PATH" || exit
  docker compose down
}

function destroy() {
  cd "$CANINE_PATH" || exit
  docker compose down --volumes --rmi all
  rm -rf "$CANINE_HOME"
}

case $1 in
  start)
    start "$2"
    ;;
  stop)
    stop
    ;;
  destroy)
    destroy
    ;;
  *)
    echo "Usage: canine [start|stop|destroy] [optional port for start]"
    exit 1
    ;;
esac
